<?php
/**
 * Created by PhpStorm.
 * User: dust2
 * Date: 14-11-17
 * Time: 下午8:00
 */

/**
 * Class AuthorityController
 * 验证模块控制器(实现系统登入、登出、注册业务)
 */
class AuthorityController extends \BaseController
{
    /**
     * 获取登入操作页面
     * @return \Illuminate\View\View
     */
    public function getLogin()
    {
        if (Auth::check()) {
            return Redirect::to('/product');
        } else {
            return View::make('authority.login');
        }
    }

    /**
     * 验证登入
     * 错误信息处理方式采用laravel验证模块相关方法处理,不进行json格式处理
     */
    public function postLogin()
    {
        $postData = Input::all();
        $password = $postData['password'];
        $username = $postData['username'];
        //通过用户名或邮箱进行登入操作
        if (Auth::attempt(['username' => $username, 'password' => $password, 'active' => true])) {
            //return Redirect::to('/product');
            return Redirect::intended('/product');
        } else {
            return Redirect::back()->withInput()->withErrors(['loginFalse'=>'登陆失败,用户名或密码错误！']);
        }
    }
    /**
     * 获取注册操作页面
     * @return \Illuminate\View\View
     */
    public function getSignup()
    {
        return View::make('authority.signup');
    }

    /**
     * 进行注册的数据校验
     * 错误信息处理方式采用laravel验证模块相关方法处理,不进行json格式处理
     *
     */
    public function postSignup()
    {
        $postData = Input::all();
        $rules = [
            'username' => 'required|unique:users',
            'password' => 'required|alpha_dash|min:6|confirmed'
            //'email' => 'required|email|unique:users'
        ];
        $validator = Validator::make($postData, $rules);

        if ($validator->fails()) {
            return Redirect::back()->withInput()->withErrors($validator);
        } else {
            $postData['password'] = Hash::make($postData['password']);
            unset($postData['password_confirmation']);
            $newUser = User::create($postData);
            Auth::login($newUser);
            if (Auth::check()) {
                return Redirect::to('/');
            } else {
                return Redirect::back()->withInput()->withErrors(['signupFalse' => '服务器内部错误,请稍后重新尝试.']);
            }
        }

    }
    /**
     * 登出操作
     */
    public function getLogout(){
        Auth::logout();
        return Redirect::to('/product');
    }

} 